/**
 * 通用工具类
 * @author 01368384，854638
 */
var constants = require('./constants.js');

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month, day].map(formatNumber).join('-')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const px2Rpx = px => {
  var screenWidth = getApp().globalData.systemInfo.screenWidth
  var factor = 750 / screenWidth;
  return factor * px;
}
/**
 * 鉴权方法封装
 */
function login(suc, fail) {
  // 登录
  wx.login({
    success: res => {
      var jsCode = res.code;
      console.log("jsCode", jsCode)
      wx.getUserInfo({
        success: res => {
          console.log("userInfo:", res.rawData)
          wx.request({
            url: constants.UrlConstants.baseUrl+'/user/getResourceId',
            method: 'POST',
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            data: { jsCode: jsCode, userInfo: res.rawData },
            success: function (res) {
              console.log('suc', res)
              if (res.statusCode == 200) {
                wx.setStorageSync(constants.StorageConstants.resourceId, res.data.data)
                wx.setStorageSync(constants.StorageConstants.userId, res.data.msg)
                if (suc) {
                  suc()
                }
              } else {
                if (fail) {
                  fail(res.data.errorCode)
                }
              }

            }
          })

        },
        fail: function (res) {
          console.log('fail', res)
          if (fail) {
            fail(res)
          }
        }

      })
    }
  })

}

/**
 * 上传图片功能
 * @param pathType  2：闪赔preRefund ，1：普通售后workOrderVoucher， 0：评价晒图commentVoucher
 * @param suc
 * @param fail
 */
function uploadImage(pathType, suc, fail) {
  var that = this;
  wx.chooseImage({
    count: 1,
    success: function (res) {
      console.log('chooseImage', res);
      var imageArr = res.tempFilePaths
      _upLoadImage(imageArr[0], pathType, suc, fail);
    },
    fail: function (res) {
      if (fail)
        fail('取消上传')
    }
  })
}
function _upLoadImage(image, pathType, suc, fail) {
  var token = wx.getStorageSync(constants.StorageConstants.tokenKey);
  var path = ''
  switch (pathType) {
    default:
    case 0:
      path = 'commentVoucher'
      break
    case 1:
      path = 'workOrderVoucher'
      break
    case 2:
      path = 'preRefund'
      break
  }
  wx.showLoading({
    title: '上传中',
    mask: true
  })
  wx.uploadFile({
    url: constants.UrlConstants.baseUrl + constants.InterfaceUrl.UPLOAD_IMG,
    filePath: image,
    header: {
      "logintoken": token
    },
    formData: {
      "path": path
    },
    name: 'file',
    success: function (res) {
      console.log(res)
      wx.hideLoading()
      var data = JSON.parse(res.data)
      if (data.errorCode == '0001') {
        if (suc)
          suc(data.result.imageUrl)
      } else {
        if (fail)
          fail('上传失败')
      }
    },
    fail: function (res) {
      console.log(res)
      wx.hideLoading()
      fail('上传失败')
    },
  })
}

const rpx2Px = rpx => {
  var screenWidth = getApp().globalData.systemInfo.screenWidth
  var factor = screenWidth / 750;
  return factor * rpx;
}

/**
 * 设置界面广告data
 */
function setAdInfo(opitons) {
  try {
    const app = getApp()
    app.globalData.adInfo.gdt_vid = opitons.gdt_vid ? opitons.gdt_vid : ''
    app.globalData.adInfo.weixinadinfo = opitons.weixinadinfo ? opitons.weixinadinfo : ''
    app.globalData.adInfo.aid = opitons.aid ? opitons.aid : ''
  } catch (e) {
    console.log('setAdInfo', '设置广告数据错误')
  }
}

module.exports = {
  formatTime: formatTime,
  px2Rpx: px2Rpx,
  rpx2Px: rpx2Px,
  login: login,
  uploadImage: uploadImage,
  setAdInfo: setAdInfo
}
